//
//  IDCardViewController.swift
//  jiaoyi
//
//  Created by wjk on 2018/8/9.
//  Copyright © 2018年 wjk. All rights reserved.
//

import UIKit
import CLImagePickerTool
import Kingfisher
import JWTDecode


class IDCardViewController: BaseViewController {

    var bl:changeUserBlock?
    
    @IBOutlet weak var btnBack: UIButton!
    @IBOutlet weak var btnBornt: UIButton!
    var data:[String:Any] = ["key":"","value":""]
    var token:String = ""
    
    var arr:NSMutableArray = NSMutableArray()
    
    var bront:Bool = false
    var back:Bool = false
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
//        self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "保存", style: .plain, target: self, action: #selector(self.save(_:)))
        
        let jd = jsonFormater(data: data)
        
        if jd["value"].stringValue.isEmpty {
            
        }else {
            
            let jwt = try? decode(jwt: String(jd["value"].stringValue.split(separator: ",").first ?? ""))
            let jwt2 = try? decode(jwt: String(jd["value"].stringValue.split(separator: ",").last ?? ""))
            let js1 = jsonFormater(data:jwt?.body as Any)
            let js2 = jsonFormater(data:jwt2?.body as Any)
            self.btnBornt.kf.setBackgroundImage(with: ImageResource.init(downloadURL: URL.init(string:js1["download"].stringValue)!), for: .normal)
            self.btnBack.kf.setBackgroundImage(with: ImageResource.init(downloadURL: URL.init(string:js2["download"].stringValue)!), for: .normal)
//            print("\(jwt!.body)")
        }
        
        // Do any additional setup after loading the view.
    }
    
    @objc func save(_ bar : UIBarButtonItem) {
        //        self.data["value"] = self.tfInput.text!
        
        
        
        if self.back == true && self.bront == true {
            
            showHUD()
            NetWorkRequest(.fileToken()) { (res) -> (Void) in
                if res["code"] as! String == "000000" {
                    let jd = jsonFormater(data: res["data"] as Any)
                    showHUD()
                    NetWorkRequest(.uploadImage(url: jd["url"].stringValue, token: jd["token"].stringValue, data: UIImageJPEGRepresentation(self.btnBornt.backgroundImage(for: .normal)!, 0.6) ?? UIImagePNGRepresentation(self.btnBornt.backgroundImage(for: .normal)!)! ), completion: { (res) -> (Void) in
                        let d2 = jsonFormater(data: res)
                        if d2["jwt"].stringValue.isEmpty == false {
                            
                            let jwt1 = d2["jwt"].stringValue
                            
                            
                            
                            showHUD()
                            NetWorkRequest(.fileToken()) { (res) -> (Void) in
                                if res["code"] as! String == "000000" {
                                    let jd = jsonFormater(data: res["data"] as Any)
                            
                            showHUD()
                            NetWorkRequest(.uploadImage(url: jd["url"].stringValue, token: jd["token"].stringValue, data: UIImageJPEGRepresentation(self.btnBack.backgroundImage(for: .normal)!, 0.6) ?? UIImagePNGRepresentation(self.btnBack.backgroundImage(for: .normal)!)! ), completion: { (res) -> (Void) in
                                let d2 = jsonFormater(data: res)
                                if d2["jwt"].stringValue.isEmpty == false {
                                    
                                    self.bl?(["key":self.data["key"] as! String,"value":"\(jwt1),\(d2["jwt"].stringValue)"])
                                    
                                    self.navigationController?.popViewController(animated: true)
                                }
                            })
                                }
                            }
                        }
                    })
                }
            }
            
        } else if self.back == false && self.bront == false {
            showMessage(message: "请先选择照片")
            return
        }else {
            let jwt = jsonFormater(data: data)
            if self.back == true {
                showHUD()
                NetWorkRequest(.fileToken()) { (res) -> (Void) in
                    if res["code"] as! String == "000000" {
                        let jd = jsonFormater(data: res["data"] as Any)
                showHUD()
                NetWorkRequest(.uploadImage(url: jd["url"].stringValue, token: jd["token"].stringValue, data: UIImageJPEGRepresentation(self.btnBack.backgroundImage(for: .normal)!, 0.6) ?? UIImagePNGRepresentation(self.btnBack.backgroundImage(for: .normal)!)! ), completion: { (res) -> (Void) in
                    let d2 = jsonFormater(data: res)
                    if d2["jwt"].stringValue.isEmpty == false {
                        self.bl?(["key":self.data["key"] as! String,"value":"\(String(jwt["value"].stringValue.split(separator: ",")[0])),\(d2["jwt"].stringValue)"])
                        self.navigationController?.popViewController(animated: true)
                    }
                })
                    }}
            }else {
                showHUD()
                NetWorkRequest(.fileToken()) { (res) -> (Void) in
                    if res["code"] as! String == "000000" {
                        let jd = jsonFormater(data: res["data"] as Any)
                NetWorkRequest(.uploadImage(url: jd["url"].stringValue, token: jd["token"].stringValue, data: UIImageJPEGRepresentation(self.btnBornt.backgroundImage(for: .normal)!, 0.6) ?? UIImagePNGRepresentation(self.btnBornt.backgroundImage(for: .normal)!)! ), completion: { (res) -> (Void) in
                    let d2 = jsonFormater(data: res)
                    if d2["jwt"].stringValue.isEmpty == false {
                        self.bl?(["key":self.data["key"] as! String,"value":"\(d2["jwt"].stringValue),\(String(jwt["value"].stringValue.split(separator: ",")[1]))"])
                        self.navigationController?.popViewController(animated: true)
                    }
                })
                    }}
            }
            
            
            
        }
        
//        self.bl?(["key":self.data["key"] as! String,"value":token])
//        self.navigationController?.popViewController(animated: true)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    @IBAction func segBack(_ sender: UIButton) {
     
        let imgp = CLImagePickerTool()
        imgp.setupImagePickerWith(MaxImagesCount: 1, superVC: self) { (asset, img) in
            //获取缩略图，耗时较短
            CLImagePickerTool.convertAssetArrToOriginImage(assetArr: asset, scale: 2, successClouse: { (i, p) in
                self.btnBack.setBackgroundImage(i, for: .normal)
                self.back = true
            }, failedClouse: {
                
            })
        }
        
    }
    
    @IBAction func segBront(_ sender: UIButton) {
        
        let imgp = CLImagePickerTool()
        imgp.setupImagePickerWith(MaxImagesCount: 1, superVC: self) { (asset, img) in
            //获取缩略图，耗时较短
            CLImagePickerTool.convertAssetArrToOriginImage(assetArr: asset, scale: 2, successClouse: { (i, p) in
                self.btnBornt.setBackgroundImage(i, for: .normal)
                self.bront = true
            }, failedClouse: {
                
            })
        }
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

    @IBAction func upload(_ sender: UIButton) {
        self.save(UIBarButtonItem())
    }
}
